package com.eastcom.mystope.commandline;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.eastcom.mystope.daemon.Launcher;
import com.eastcom.mystope.daemon.extern.db.config.Enviroment;
import com.eastcom.mystope.daemon.extern.db.config.Record;
import com.eastcom.mystope.daemon.extern.db.config.Task;
import com.eastcom.mystope.daemon.extern.db.context.TaskContext;
import com.eastcom.mystope.daemon.extern.db.quarzjob.BuCaiJob;
import com.eastcom.mystope.daemon.extern.db.quarzjob.NormalJob;
import com.eastcom.mystope.daemon.tools.TaskUtil;
public class ServerCommandIoHandler extends IoHandlerAdapter {

	private static Log logger = LogFactory.getLog(ServerCommandIoHandler.class);


	public void exceptionCaught(IoSession session, Throwable cause)
			throws Exception {
		super.exceptionCaught(session, cause);

	}

	public void sessionClosed(IoSession session) throws Exception {
		super.sessionClosed(session);
		logger.debug("Command session closed ....");
	}

	public void sessionCreated(IoSession session) throws Exception {
		super.sessionCreated(session);
	}

	public void sessionIdle(IoSession session, IdleStatus status)
			throws Exception {
		super.sessionIdle(session, status);
	}

	public void sessionOpened(IoSession session) throws Exception {
		super.sessionOpened(session);
	}

	public void messageReceived(IoSession session, Object message)
			throws Exception {
		super.messageReceived(session, message);
		System.out.println(message.toString());
		if(message instanceof String){
			String[] cmd = ((String)message).split("-");
			System.out.println("接收到客户端命令："+cmd.length);
			if(cmd[0].equalsIgnoreCase("dbbucai")){
				if(cmd.length < 2){
					session.write("useage:[dbbucai-任务名 ]");
					return;
				}
				//				ServerContext enviroment = TaskContext.enviroment;
				Task task = TaskContext.normalTaskInfoMap.get(cmd[1]);
				logger.debug(task);
				Task taskNew = task.deepClone();
				taskNew.setName(task.getName()+"_new_"+new Date().getTime());
				List<Record> recordList = task.getRecordConfig().getRecords();
				taskNew.getRecordConfig().setRecords(new ArrayList<Record>());
				for(Record record: recordList){
					Record recordNew = TaskUtil.getRecordByNewTime(task.getName(),record, new Timestamp(new Date().getTime()));
					taskNew.getRecordConfig().getRecords().add(recordNew);
				}
				//					NormalJob.doMyTask(taskNew);
				BuCaiJob.doExternJob(taskNew);
			}else if(cmd[0].equals("stop")){
				Launcher.notifyLock();
				System.exit(0);
			}
		}
	}

}
